package top.codedance.iotp.client.plugins.sync.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.ClientApplication;
import top.codedance.iotp.common.executer.SyncAbstractExecuter;
import top.codedance.iotp.common.entity.PluginResultEntity;
import top.codedance.iotp.common.util.OSinfo;
import top.codedance.iotp.common.util.SystemUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class ClientBootParamsSetExecuterImpl extends SyncAbstractExecuter {

    @Override
    public PluginResultEntity exec(byte[] data, String taskId) {
        PluginResultEntity result = new PluginResultEntity();
        try {
            String body = new String(data, StandardCharsets.UTF_8);
            JSONObject jo = JSON.parseObject(body);
            String file = jo.getString("file");
            if(file.equals("")){
                if(OSinfo.isWindows()){
                    file = ClientApplication.getJarDirPath() + "../" + "conf";
                }else{
                    file = "/etc/supervisord.d";
                    if(!new File(file).exists()) {
                        file = "/etc/supervisor/conf.d";
                    }
                }
            }
            if(!file.endsWith("/")){
                file = file + "/";
            }
            String fileName;
            if(OSinfo.isWindows()){
                fileName = "wrapper.conf";
                file = file + fileName;
            }else{
                fileName = "iot-client.ini";
                if(!new File(file + fileName).exists()){
                    fileName = "iot-manage.ini";
                    if(!new File(file + fileName).exists()){
                        fileName = "iot-manage.conf";
                        if(!new File(file + fileName).exists()){
                            fileName = "iot-client.conf";
                        }
                    }
                }
                file = file + fileName;
            }
            if(new File(file).exists()) {
                String fileData = jo.getString("data");
                SystemUtil.writeFile(file, fileData);
                result.setOk(true);
                result.setContext("Success");
            }else{
                result.setOk(false);
                result.setMsg("Config file is not found.");
            }
        }catch (Exception ex){
            result.setOk(false);
            result.setMsg(ex.getMessage());
        }
        return result;
    }
}
